package org.wei.utils.exception;

import java.util.HashSet;
import java.util.Set;

import org.wei.utils.DateUtil;
import org.wei.utils.IOUtil;

public class LogHelper {

	private static final String formatter = "\n exception :%s \n with message:%s \n with stacktrace:";
	private final Set<String> classNameFilters = new HashSet<String>();
	private String dir = "/var/log/default/";

	private LogHelper() {
	}

	private static LogHelper instance;

	public static LogHelper getInstance() {
		if (instance == null) {
			instance = new LogHelper();
		}
		return instance;
	}

	public void info(Exception e) {
		log(e, "[INFO]");
	}

	private void log(Exception e, String prefix) {
		StackTraceElement[] traceElements = e.getStackTrace();
		String message = String.format(prefix + formatter, e.getClass()
				.getName(), e.getMessage());
		StringBuilder sb = new StringBuilder(message);
		for (StackTraceElement stackTraceElement : traceElements) {
			String trace = stackTraceElement.toString();
			for (String filter : classNameFilters) {
				if (trace.startsWith(filter)) {
					sb.append(stackTraceElement.toString() + "\n");
					break;
				}
			}
		}
		sb.append(DateUtil.nowDate2String()).append("\n");
		IOUtil.appendLineToFile(getDir(), DateUtil.nowDate2String("YYMMdd")
				+ ".log", sb);
	}

	private void log(String message, String prefix) {
		IOUtil.appendLineToFile(getDir(), DateUtil.nowDate2String("YYMMdd")
				+ ".log", prefix + message);
	}

	public void debug(Exception e) {
		log(e, "[DEBUG]");
	}
	
	public void warn(Exception e) {
		log(e, "[WARN]");
	}

	public void error(Exception e) {
		log(e, "[ERROR]");
	}

	public void debug(String message) {
		log(message, "[DEBUG]");
	}

	public void info(String message) {
		log(message, "[INFO]");
	}

	public void warn(String message) {
		log(message, "[WARN]");
	}

	public void error(String message) {
		log(message, "[ERROR]");
	}

	public Set<String> getClassnamefilters() {
		return classNameFilters;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public static void main(String[] args) {
		System.out.println(DateUtil.nowDate2String("HHmmss"));
	}
}
